#include "TcpServer.h"

#include <utility>

#include "functional"

TcpServer::TcpServer(const InetAddress &listenAddr, std::string name) :
        name_(std::move(name)),
        acceptor_(new Acceptor(listenAddr)),
        started_(false),
        nextConnId_(1){
    acceptor_->setNewConnectionCallback(
            std::bind(&TcpServer::newConnection, this, std::placeholders::_1, std::placeholders::_2));
}

TcpServer::~TcpServer() {

}

void TcpServer::newConnection(int sockfd, const InetAddress &peerAddr) {
    char buf[32];
    snprintf(buf, sizeof buf, "#%d", nextConnId_);
    ++nextConnId_;
    std::string connName = name_ + buf;
    InetAddress localAddr(Socket::getLocalAddr(sockfd));
    // 获取本地sock对应的地址信息, 然后存放到conn指针总
    TcpConnectionPtr conn(new TcpConnection(connName, sockfd, localAddr, peerAddr));
    connections_[connName] = conn;
    // 将分配的新连接管理类保存卡里
    conn->setConnectionCallback(connectionCallback_);
    conn->setMessageCallback(messageCallback_);
    conn->setCloseCallback(closeCallback_);
}

void TcpServer::removeConnection(const TcpConnectionPtr &conn) {
    ssize_t n = connections_.erase(conn->getName());
    // 移除conn, 同时调用这个conn对应的移除函数
    // 负责移除这个连接对应的回调函数, 移除了这些回调函数之后没有Socket没有指向会被智能指针自动析构
    conn->connectDestroyed();
}

void TcpServer::start() {
    acceptor_->listen();
    // 这里监听到之后acceptor会调用我们的newConnection函数去获取处理连接
    fprintf(stderr, "调用\n");
    for(auto it : connections_){
        it.second->connectionCallback_(it.second);
    }
}